package pers.lan.hash;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <p><a href="mailto:1728209643@qq.com">XiaoSan</a>
 * @date 2019/9/16 9:15 AM
 */
public class LC_811 {

    public static void main(String[] args) {
        System.out.println(
                new LC_811().subdomainVisits(new String[]{
                        "900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"
                })
        );
    }

    public List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < cpdomains.length; i++) {
            int i1 = cpdomains[i].indexOf(" ");

            int time = Integer.parseInt(cpdomains[i].substring(0, i1));
            String domains = cpdomains[i].substring(i1);
            String[] split = domains.split("\\.");
            for (int j = 0; j < split.length; j++) {
                StringBuilder domain = new StringBuilder();
                for (int k = j; k < split.length; k++) {
                    domain.append(split[k]).append(".");
                }
                map.put(domain.toString(), map.getOrDefault(domain.toString(), 0) + time);
            }
        }

        List<String> res = new ArrayList<>(map.size());
        map.forEach((dm, t) -> res.add(t + " " + dm.substring(0, dm.length() - 1)));

        return res;
    }
}
